<!--
调用必须传的参数:oldimgs（图片的相关数据展示作用，可为空）
图片选择可配置选项：
 1.picDel：是否存在删除按钮（true，false），默认存在（true;
 2.picAdd：是否存在图片添加按钮（true，false），默存在（true;
 3.maxCount：图片最多存在数量（默认9张;
 4.deviceVersions:设备版本（默认移动端phone,pc,picShow,picPrviewerShow）,注：picShow只提供展示功能,picPrviewerShow只提供展示预览功能
 5.picWidth:设置多张图片的尺寸（类似15px,15rem,15vw）,singPicWidth:设置单张图片的尺寸,mulPicWidth:设置两张图片的尺寸
回调函数：
  returnData = this.$refs.picRef.returnData();
  returnData:接收组件内最终数据
  picRef:为区分组建的标志，在组件中名字自定义（ref="picRef"）
  返回数据格式:{newImgs:["http","http"],oldImgs:[{id:xxx,src:xxx}]}
  isPreviewerClose：是否由预览图片状态返回
属性判断：
  isPreviewer：当存在时表示正在预览图片
  -->
<template>
  <div class="picSelected" :isPreviewer="isPreviewer">
    <!--移动端执行-->
    <div v-if="deviceVersions=='phone'" class="picIphone">
      <!--移动端老数据-->
      <div v-show="initialShow" class="addPic" v-for="(imgs,index) in oldimgWrap" :style="{width:picWidth+'vw',height:picWidth+'vw'}">
        <img class="addImg"
             v-lazy="imgs.src"
             alt=""
             v-preview="imgs.src"
             :alt="tips"
             preview-title-enable="true"
             preview-nav-enable="false"
        >
        <span v-show="picDel" :index="index" class="olddelImg" @click="delImg(index,1)"></span>
      </div>
      <!--移动端新建-->
      <div class="addPic" v-for="(imgs,index) in returnPiclocalId" :style="{width:picWidth,height:picWidth}">
        <img class="addImg"
             :src="imgs"
             alt=""
             v-preview="imgs.src"
             :alt="tips"
             preview-title-enable="true"
             preview-nav-enable="false">
        <span v-show="picDel" :index="index" class="newdelImg" @click="delImg(index,0)"></span>
      </div>
      <div v-if="picAdd" v-show="picCount" @click="selectPic(0)" class="addPicIcon"></div>
    </div>
    <!--pc端执行的-->
    <div v-if="deviceVersions=='pc'" class="picSelectedPc" :isPreviewer="isPreviewer">
      <div v-show="initialShow" class="addPic" v-for="(imgs,index) in pcPicTotal" :style="{width:picWidth,height:picWidth,marginRight:pcimgRight}">
        <img v-lazy="imgs.src"
             v-preview="imgs.src"
             :alt="tips"
             preview-title-enable="true"
             preview-nav-enable="false" class="addImg">
        <span class="olddelImg" v-show="picDel" :index="index" @click="delimgs(1,index)"></span>
      </div>
      <div v-transfer-dom>
        <previewer @on-close="previewerClose" :list="computedPreviewerData" ref="previewer1" :options="options1"></previewer>
      </div>
      <div v-if="picAdd" v-show="addCount" class="addPicIcon" @click="addPic" :style="{width:picWidth,height:picWidth,marginRight:pcimgRight}"></div>
      <input type="file" accept="image/*"  multiple ref="picChoseDom" v-show="false" @change="picInputChange()">
    </div>
    <!--只图片展示功能-->
    <div v-if="deviceVersions=='picShow'" class="picShow">
      <div class="imgs-line" v-if="picShowData.length>1">
        <img
          class="multiImg"
          v-for="(img,index) in picShowData"
          v-if="index<3"
          :style="{width:mulPicWidth,height:mulPicWidth}"
          v-lazy="img.url"
          v-preview="imgs.src"
          :alt="tips"
          preview-title-enable="true"
          preview-nav-enable="false"
        />
      </div>
      <div class="imgs-line" v-if="picShowData.length==1">
        <img
          class="singleImg"
          :style="{maxWidth:singPicWidth,maxHeight:singPicWidth}"
          v-for="(img,index) in picShowData"
          v-if="index<3"
          v-preview="imgs.src"
          :alt="tips"
          preview-title-enable="true"
          preview-nav-enable="false"
          v-lazy="img.url"/>
      </div>
    </div>
    <!--详情图片预览功能-->
    <div v-if="deviceVersions=='picPrviewerShow'" class="picShow" :isPreviewer="isPreviewer">
      <div class="imgsPrew imgs-line" v-if="picShowPrviewer.length==1">
        <span v-if="index<3" class="imgsPrews" v-for="(imgs,index) in picShowPrviewer">
          <img  class="singleImg"
                v-lazy="imgs.src"
                v-preview="imgs.src"
                :alt="tips"
                preview-title-enable="true"
                preview-nav-enable="false"
          />
        </span>
      </div>
      <div class="imgsPrew imgs-line" v-if="picShowPrviewer.length==2">
        <span v-if="index<3" class="imgsPrews" v-for="(imgs,index) in picShowPrviewer">
          <img
            class="multiImg"
            :style="{width:mulPicWidth,height:mulPicWidth}"
            v-preview="imgs.src"
            :alt="tips"
            preview-title-enable="true"
            preview-nav-enable="false"
            v-lazy="imgs.src"/>
        </span>
      </div>
      <div class="imgs-lines" v-if="picShowPrviewer.length>2">
        <span class="imgsPrews" v-for="(imgs,index) in picShowPrviewer">
          <img
            class="manyImg"
            :style="{width:picWidth,height:picWidth,marginRight:imgRight}"
            v-preview="imgs.src"
            :alt="tips"
            preview-title-enable="true"
            preview-nav-enable="false"
            v-lazy="imgs.src"/>
        </span>
      </div>
      <div v-transfer-dom>
        <previewer  @on-close="previewerClose" :list="computedPreviewerShowData" ref="previewer2" :options="options2"></previewer>
      </div>
    </div>
  </div>
</template>
<script>
  import vue from 'vue';
  import tools from '@/utils/common';
  import {TransferDom,LoadingPlugin,Previewer,ToastPlugin} from 'vux';
  vue.use(ToastPlugin);
  vue.use(Previewer);
  vue.use(LoadingPlugin);
  export default {
    name:'picSelected',
    props:{
      picDel:{//是否存在图片删除按钮
        type: Boolean,
        default: true,
      },
      picAdd:{//是否存在图片添加按钮
        type: Boolean,
        default: true,
      },
      maxCount:{//图片最多存在数量
        type: Number,
        default: 9,
      },
      oldimgs:{//是否存在图片数据
        type:Array,
        default:[],
      },
      deviceVersions:{//设备版本（默认pc）
        type: String,
        default: 'pc'
      },
      picWidth:{//多张图片宽度(至少3张)
        type:String,
        default:'16vw'
      },
      singPicWidth:{//单张图片宽度
        type:String,
        default:'16vw'
      },
      mulPicWidth:{//两张图片宽度
        type:String,
        default:'16vw'
      },
      imgRight:{
        type:String,
        default:'0.08rem',
      },
      pcimgRight:{
        type:String,
        default:'0.2rem',
      }
//      isPreviewer:{//是否进入预览
//        type:Boolean,
//        default:false,
//      },
    },
    components:{
      Previewer,
      ToastPlugin,
    },
    directives: {
      TransferDom
    },
    data(){
      return{
        isPreviewer:false,
        tips:"点击关闭",
        initialShow:true,
        oldimgWrap:[],//老图片包裹元素
        picSelectTotal:{},//移动端图片数量计算
        returnPic:[],//移动端数据集合
        imgSrc:[],
        picServeId:[],//移动端上传图片id
        picSelectTotal:{localId: [], serverId: []},//移动端轻推数组集合
        previewerData:[],//预览图片集合
        //pc端数据汇总
        addCount:true,
        picSelectedData:[],//存储选择图片数据
        picType:'',//图片类型(0:新建，1:修改)
        oldImgWrap:[],//老图片包裹元素
        oldImgWraps:[],//展示及预览图片
        previewerShowData:[],//只展示预览图片
        options1: {//pc图片预览
          getThumbBoundsFn (index) {
            let thumbnail = document.querySelectorAll('.addPic')[index]
            let pageYScroll = window.pageYOffset || document.documentElement.scrollTop
            let rect = thumbnail.getBoundingClientRect()
            return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}
          }
        },
        options2:{//展示图片预览
          getThumbBoundsFn (index) {
            let thumbnail = document.querySelectorAll('.imgsPrews')[index]
            let pageYScroll = window.pageYOffset || document.documentElement.scrollTop
            let rect = thumbnail.getBoundingClientRect()
            return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}
          }
        }
      }
    },
    mounted:function(){

      let vue = this
      vue.$nextTick(function () {

//        vue.oldImgWrap = vue.oldimgs
//        vue.oldimgWrap = vue.oldimgs
//        vue.previewerData = vue.oldimgs

        //老数据分割显示的
//        if(vue.oldimgs == ''||undefined||null){
//          vue.initialShow = false
//        }else{
//          vue.oldimgWrap = vue.oldimgs.split(',');
//          if(vue.deviceVersions == 'pc'){
//            vue.oldImgWrap = vue.oldimgs.split(',');
//            let aaa={}
//            for(let i=0;i<vue.oldImgWrap.length;i++){
//              aaa = {src:vue.oldImgWrap[i]}
//              vue.previewerData.push(aaa)
//            }
//          }
//        }
      })
    },
    methods:{
      //点击添加图片按钮，调用轻推接口
      selectPic:function (type) {
//        console.info('this is selectPic')
        let vm = this;
        let maxCounts = vm.maxCount;//自定义最多可选择图片
        let newCount = vm.returnPic.length;
        let oldCount = vm.oldimgs
        let imgLen = maxCounts-oldCount-newCount;
        qt.chooseImage({
          count: imgLen, // 默认9，可自定义
          sizeType: ['compressed'], // original，compressed可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function(res) {
//            console.info('this is success')
            imgLen = res.localIds.length+vm.returnPic.length;
            vm.imgSrc = res.localIds;
            vm.returnPic.push.apply(vm.returnPic,vm.imgSrc);
            vm.picSelectTotal.localId = vm.picSelectTotal.localId.concat(res.localIds);
          }
        });
      },
      //上传图片
      upPicData:function () {
        let that = this,result = {
          localId: that.returnPic,
          serverId: []
        },i=0,length=that.returnPic.length;
        that.$vux.loading.show({
          text: '正在上传:'+1+'/'+length
        });
        function upload() {
          that.$vux.loading.show({
            text: '正在上传:'+(i+1)+'/'+length
          });
          qt.uploadFile({
            localId: that.returnPic[i], // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 0, // 默认为1，显示进度提示
            success: function(res) {
              i++;
//              alert('已上传' + i);
//              alert(res.serverId)
              result.serverId.push(res.serverId);
              if (i < length) {
                upload();
              }else if(i = length){
                that.$vux.loading.hide()
                return result
              }
            },
            fail: function(res) {
              alert(res.errMsg);
            }
          });
        }
        upload();
//        return result
      },
      //删除图片（删除对应的localId）
      delImg:function(index,type){
        let that = this;
        let invertedServerID = [];
        if(type == 1){//老图片删除
          that.oldimgWrap.splice(index,1);
        }else{//新图片删除
//          console.info('this is new img delete')
//          console.info(index);
          that.returnPic.splice(index,1);
        }
      },
      //点击预览(调用轻推接口)
      picPreview:function(e,type){
        let vue = this;
        let currUrl = $(e.target).attr("src");
        let sss = []
        for(let i=0,imgArr;imgArr=vue.oldimgs[i++];){
          sss.push(imgArr.src)
        }
        let previewSrc = sss.concat(vue.returnPic)
//        console.info(previewSrc)
        qt.previewImage({
          btns:["forward","download"],// 界面按钮，forward转发按钮，download下载按钮(没看懂，先放着)
          current: currUrl, // 当前显示图片的http链接
          urls: previewSrc, // 需要预览的图片http链接列表
        });
      },
      //点击添加图片(pc)
      addPic:function(){
        this.$refs.picChoseDom.click();
      },
      //图片添加/改变(pc)
      picInputChange:function () {
        let vue = this;
        let picDom=vue.$refs.picChoseDom;
        let choseImgNum=picDom.files.length;
        let totalImgNum=0;
        //文件格式检测
        for(let j=0;j<picDom.files.length;j++){
          let type=picDom.files[j].name;
          if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(type)){
            vue.$vux.toast.show({text: '请选择图片',type:"warn",isShowMask:true});
            $(picDom).val('');
            return false;
          }
        }
        totalImgNum=vue.oldImgWrap.length+choseImgNum;
        //最多n张图片(默认为9，可自定义)
        if(totalImgNum>vue.maxCount){
          vue.$vux.toast.show({text: '最多'+vue.maxCount+'张图片',type:"warn",isShowMask:true});
          $(picDom).val('');
          if(totalImgNum>0){
            vue.initialShow=true
          }
        }else{
          if(totalImgNum==vue.maxCount){
            vue.addCount = false;
//            $(picDom).val('');
          }
         /* vue.$store.dispatch("updateAppLoading",true);*/
          tools.readFilesToBase64(picDom.files).then(function (data) {
            let picData=[];
            if(data.length>0){
              vue.initialShow=true;
//              vue.previewerData.push.apply(vue.previewerData,data)
              vue.oldImgWrap.push.apply(vue.oldImgWrap,data);
              $(picDom).val('');
            }
            //解决不能选择相同图片的问题
            $(picDom).val('');
            setTimeout(function () {
          /*    vue.$store.dispatch("updateAppLoading",false);*/
            },300);
          });
        }
//        $(picDom).val('');
      },
      //图片删除(pc)
      delimgs:function (type,index) {
        let vue = this;
        vue.oldImgWrap.splice(index,1);
//        vue.previewerData.splice(index,1)
        if(vue.maxCount > vue.oldImgWrap.length){
          vue.addCount = true
        }
      },
      //图片预览(pc只展示以及预览)
      previewerPic:function (index,type) {
//        console.info(type)
        let vue = this;
        vue.$router.push({path: this.$router.currentRoute.path+'/preview'});
        if(vue.deviceVersions=='pc'){
          vue.$refs.previewer1.show(index);
          vue.isPreviewer = true;
        }
      },
      previewerPic2:function (index,type) {
        let vue = this;
        vue.$router.push({path: this.$router.currentRoute.path+'/preview'});
        if(vue.deviceVersions=='picPrviewerShow'){
          vue.$refs.previewer2.show(index);
          vue.isPreviewer = true;
        }
      },
      //图片预览关闭事件
      previewerClose:function () {
        if(this.isPreviewer){//还要判断不是轻推
          setTimeout(function () {
            history.go(-1);
          },30)
        }
        this.isPreviewer = false;

      },
      //是否由预览页面返回
      isPreviewerClose:function () {
        let vm = this;
        if(vm.deviceVersions == 'pc'){
          vm.$refs.previewer1.close();
        }else if(vm.deviceVersions=='picPrviewerShow'){
          vm.$refs.previewer2.close();
        }

      },
      stopPreviwer:function () {
//        console.info('2222222222222221111111111111')
      },
      //触发返回数据
      returnData:function(){
        let vue = this;
        let returnData = {};
        if(vue.deviceVersions == 'pc'){
//          console.info(vue.oldImgWrap)
          returnData = vue.buildImgs(vue.oldImgWrap);
        }else{
          returnData.oldImgs = vue.oldimgWrap;
          returnData.newImgs = vue.returnPic;
        }
//        console.info(returnData)
        return returnData
      },
      /**
       * 构建图片集合
       * newImgs:新图片
       * oldImgs:历史图片
       * @param imgs
       */
      buildImgs:function(imgs) {
        let returnData=new Object();
        let newImgs=new Array();//新图片数组
        let oldImgs=[];//历史图片通过逗号隔开
        for(let i=0,imgsArr;imgsArr=imgs[i++];){
          let jsonImg=JSON.stringify(imgsArr);
          let imgObject=JSON.parse(jsonImg);
//          console.info(imgObject.id)
          if(imgObject.id==""||imgObject==null||imgObject==undefined){
            newImgs.push(imgObject.src);
          }else{
            oldImgs.push(imgObject);
//            if(oldImgs==""){
//              oldImgs+=imgObject;
//            }else{
//              oldImgs+=","+imgObject;
//            }
          }
        }
        returnData.newImgs=newImgs;
        returnData.oldImgs=oldImgs;
//        console.info(returnData)
        return returnData;
      },
    },
    computed:{
      //展示数据计算
      picShowData:function () {
        let vue = this;
        vue.oldImgWrap = vue.oldimgs;
        return vue.oldImgWrap;
      },
      //展示预览数据计算
      picShowPrviewer:function () {
        let vue = this;
        vue.oldImgWraps = vue.oldimgs;
//        for(let i in vue.oldImgWraps){
//          console.info(vue.oldImgWraps[i])
//        }
        return vue.oldImgWraps;
      },
      //计算选择的新图片数量变化
      returnPiclocalId:function () {
          let that = this;
          return that.returnPic;
      },
      //图片数量判断
      picCount:function () {
        let that = this;
        let picLen = that.returnPic.length + that.oldimgWrap.length;
        let max = that.maxCount;
        if(picLen >= max){
          return false
        }else{
          return true
        }
      },
      //pc图片数据
      pcPicTotal:function () {
        this.oldImgWrap = this.oldimgs;
        return this.oldImgWrap
      },
      //pc预览图片计算
      computedPreviewerData:function () {
        this.previewerData = this.oldimgs;
        return this.previewerData
      },
      //展示及预览图片计算
      computedPreviewerShowData:function () {
        this.previewerShowData = this.oldimgs;
        return this.previewerShowData
      }
    },
    watch:{
      '$route' (to, from) {
        let vm = this;
        if(from.name=='preview'&&vm.isPreviewer&&vm.deviceVersions=='picPrviewerShow'){
          vm.isPreviewer = false;
          vm.$refs.previewer2.close();
        }else if(from.name=='preview'&&vm.isPreviewer&&vm.deviceVersions=='pc'){
          vm.isPreviewer = false;
          vm.$refs.previewer1.close()
        }
      },
    },
  }
</script>
<style scoped>
  .picSelectedIphone{

  }
  .picSelectedPc{
    margin-top: .1rem;
    display: flex;
    flex-wrap: wrap;
  }
  .picIphone{
    margin-top: .1rem;
    display: flex;
    flex-wrap: wrap;
  }
  .addPic{
    width: 25vw;
    height: 25vw;
    margin-right: .2rem;
    margin-bottom: .2rem;
    flex-shrink: 0;
    position: relative;
  }
  .addPic .addImg{
    width: 100%;
    height: 100%;
    border-radius: .06rem;
    cursor: pointer;
    object-fit: cover;
    object-position: 50% 50%;
  }
  .addPic .olddelImg,.newdelImg{
    top: 0;
    right: 0;
    width: 25px;
    height: 25px;
    transform: translate(6px,-6px);
    background-size: 95% 95%!important;
    position: absolute;
    background: url("../assets/img/ico/del-pic-icon.svg") no-repeat;
  }
  .addPicIcon{
    width: 25vw;
    height: 25vw;
    background-size: 100% 100%!important;
    display: flex;
    justify-content: flex-end;
    margin-right: .2rem;
    margin-bottom: .2rem;
    flex-shrink: 0;
    box-shadow: 0 1px 4px 2px rgba(145,145,145,0.10);
    background: url('../assets/img/ico/add-pic-icon.svg');
  }

  /*图片展示样式*/
  .picShow .imgs-line {
    line-height: 1.5;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: .16rem;
  }

  .picShow .imgs-line .multiImg {
    width: 25vw;
    height: 25vw;
    margin-right: .08rem;
    margin-top: .08rem;
    border-radius: .06rem;
    object-fit: cover;
    object-position: 50% 50%;
  }

  .picShow .imgs-line .singleImg {
    max-height: calc(75vw + .24rem);
    max-width: 75vw;
    margin-right: .08rem;
    margin-top: .08rem;
    border-radius: .06rem;
  }
  .picShow .imgs-lines {
    line-height: 1.5;
    /*display: flex;*/
    /*flex-wrap: wrap;*/
    /*justify-content: flex-start;*/
    /*align-items: center;*/
    margin-top: .16rem;
  }
  .picShow .imgs-lines .manyImg{
    width:25vw;
    height: 25vw;
    margin-right: .08rem;
    margin-top: .08rem;
    border-radius: .06rem;
    object-fit: cover;
    object-position: 50% 50%;
  }
</style>
